package com.handong.handserialprogram.module.qrscan.update;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.module.tasklist.TaskListActivity;
import com.handong.handserialprogram.ui.radar.RadarScanView;
import com.handong.handserialprogram.utils.DialogUtils;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.handong.handserialprogram.utils.modem.YModem;
import com.handong.handserialprogram.utils.modem.YModemListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.pda.serialport.SerialPort;
import cn.pda.serialport.Tools;


public class FootUpdateActivity extends FragmentActivity implements View.OnClickListener {
    private String TAG = "FootUpdateDate";
    //信息显示的Fragment
    private FrameLayout find_page, mes_page;
    private RadioButton rb1, rb2;
    private TextView headerCenterTitle, mBtnStarDownload,updateOnline;
    private RadarScanView radarScanView;
    private RecyclerView searchRingRecycler;
    private SerialPortUtil mSerialPortUtil;
    private List<FootRingNewEntity> mFootRinglist;
    private UpdateRingAdapter mRingAdapter;
    private int position;
    private YModem ymodem;
    private boolean ringsCanUpdate;
    private ImageView headerImage;

    private TextView mEt_file;
    private File mFirmwareFile;
    private String path;
    private SerialPort mSerialPort;
    private InputStream mReadStream;
    private OutputStream mWriteStream;
    private Boolean canGet = false;

    private Context mContext;
    private CopyOnWriteArrayList<FootRingNewEntity> mList;
    private Thread getSomeDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foot_update);
        mContext = FootUpdateActivity.this;
        initUI();
        initDate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        scanAroundFootRing();
        radarScanView.startAnimation();
        find_page.setVisibility(View.VISIBLE);

    }

    //接收信息做升级处理
    boolean canStop;

    private void doWork() {
        if ((this.mReadStream == null) || (this.mWriteStream == null)) {
            Log.d(TAG, "byte:" + null);

            this.mReadStream = this.mSerialPort.getInputStream();
            this.mWriteStream = this.mSerialPort.getOutputStream();
        }
        while (canStop) {
            try {
                if (mReadStream.available() > 0) {
                    byte[] buff = new byte[mReadStream.available()];//获取全部数据
                    mReadStream.read(buff);
                    Log.d(TAG, "xxxx：" + Arrays.toString(buff));
                    if (buff.length < 3) {
                        Log.d(TAG, "xxxx：" + Arrays.toString(buff));
                        if (canGet) {
                            ymodem.onReceiveData(buff);
                        }
                    }
                }
            } catch (IOException e) {
                Log.d(TAG, e.toString());
                e.printStackTrace();
            }
        }
    }

    //初始化端口信息
    private void initPort() {
        Log.d("YMODEM", "开始初始化数据");
        mSerialPort = new SerialPort();
        mSerialPort.rfid_poweron();
        try {
            mSerialPort.openSerial(13, 115200);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, e.toString());
        }
    }

    private void initDate() {
        mSerialPort = new SerialPort();
        headerCenterTitle.setText("");
        mBtnStarDownload.setVisibility(View.VISIBLE);
        findViewById(R.id.headerOptionLayout).setVisibility(View.VISIBLE);
        mBtnStarDownload.setText("确定");

        rb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rb2.setChecked(false);
                }
            }
        });
        rb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rb1.setChecked(false);
                    updateOnline.setText("无可用文件");
                }
            }
        });

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (radarScanView.isShown()) {
            radarScanView.stopAnimation();
        }
        EventBusUtil.unRegister(this);
        mSerialPortUtil.closeSerialPort();

        if (ymodem != null) {
            ymodem.stop();
        }

    }

    private void startTransmission() {
        Log.d(TAG, "开始传输=====");
        ymodem = new YModem.Builder()
                .with(this)
                .filePath("file://" + path)
                .fileName(mFirmwareFile.getName())
                .callback(new YModemListener() {
                    @Override
                    public void onDataReady(byte[] data) {
                        Log.d(TAG, "onDataReady :长度" + data.length + "内容：" + Tools.bytes2HexString(data));
                        beginFileInput(data);
                    }

                    @Override
                    public void onProgress(final int currentSent, final int total) {

                        Log.d(TAG, "onProgress 。。。。" + "currentSent:" + currentSent + "total:" + total+"%"+(int) ((currentSent /(float) total) * 100));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showLoadDialog("升级固件传输中(" + (int) ((currentSent /(float) (total+2048)) * 100) + "%)");
                            }
                        });
                    }

                    @Override
                    public void onSuccess() {
                        dismissLoadingDialog();
                        canGet = false;
                        canStop = false;
                        Intent intent = new Intent(mContext, TaskListActivity.class);
                        startActivity(intent);

                    }

                    @Override
                    public void onFailed(final String reason) {
                        dismissLoadingDialog();
                        canGet = false;
                        canStop = false;

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(FootUpdateActivity.this, reason, Toast.LENGTH_SHORT).show();
                                if (!radarScanView.isShown()) {
                                    radarScanView.startAnimation();
                                    mes_page.setVisibility(View.GONE);
                                    find_page.setVisibility(View.VISIBLE);
                                    scanAroundFootRing();
                                }
                            }
                        });


                    }
                }).build();

        ymodem.start();
        canGet = true;
    }

    private void beginFileInput(byte[] data) {
        if ((this.mReadStream == null) || (this.mWriteStream == null)) {
            Log.d(TAG, "流为空");
            this.mReadStream = this.mSerialPort.getInputStream();
            this.mWriteStream = this.mSerialPort.getOutputStream();
        }
        try {
            this.mWriteStream.write(data);
            Log.d(TAG, "写入数据长度：" + data.length);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "循环发送命令" + Tools.byteToHexString(data) + "。");
        }
    }

    private void initUI() {
        find_page = findViewById(R.id.update_find_page);
        find_page.setOnClickListener(this);
        mes_page = findViewById(R.id.update_mes_page);
        updateOnline=findViewById(R.id.updateOnline);
        mEt_file = findViewById(R.id.et_file_show);
        mBtnStarDownload = findViewById(R.id.headerOptionItem);
        radarScanView = findViewById(R.id.searchRingRadarScan);
        headerCenterTitle = findViewById(R.id.headerCenterTitle);
        searchRingRecycler = findViewById(R.id.searchRingRecycler);
        rb1 = findViewById(R.id.radioButton_1);
        rb2 = findViewById(R.id.radioButton_2);
        findViewById(R.id.et_file_show).setOnClickListener(this);
        findViewById(R.id.headerOptionItem).setOnClickListener(this);

        headerImage=findViewById(R.id.headerBackLayoutIcon);
        headerImage.setImageResource(R.drawable.ic_menu_back_144);
        findViewById(R.id.headerBackLayout).setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();

    }
    //判断以什么结尾
    private boolean endWith() {
        String fileName = mFirmwareFile.getName();
        String[] names = fileName.split("\\.");
        String tab = names[names.length - 1];
        if (tab.equals("bin")) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headerBackLayout:
                onBackPressed();
                finish();
                break;
            case R.id.et_file_show:
                DialogUtils.select_file(FootUpdateActivity.this, new DialogUtils.DialogSelection() {
                    @Override
                    public void onSelectedFilePaths(String[] files) {
                        if (files[0].split("\\.")[files[0].split("\\.").length - 1].equals("bin")) {
                            path = files[0];
                            mFirmwareFile = new File(files[0]);
                            String versionStr = mFirmwareFile.getName().split("-V")[1].split("\\.bin")[0];
                            mEt_file.setText("升级版本：V" + versionStr);
                        } else {
                            mEt_file.setText("请选择以 .bin 结尾的文件");
                        }
                    }
                });
                rb1.setChecked(true);
                break;
            case R.id.headerOptionItem:  //开始文件传输
                if (rb1.isChecked()) {
                    if (mFirmwareFile != null && mFirmwareFile.exists() && endWith()) {
                        beginReadyFileTrans();
                    } else {
                        Toast.makeText(mContext, "选择一个合法的bin文件", Toast.LENGTH_SHORT).show();
                    }
                } else if (rb2.isChecked()) {
                    Toast.makeText(mContext, "当前已是最新版本，无需更新", Toast.LENGTH_SHORT).show();
//                    MaterialDialog dialog = new MaterialDialog.Builder(mContext)
//                            .title("版本更新")
//                            .content("是否更新到v" + "???" + "版本？")
//                            .canceledOnTouchOutside(false)
//                            .positiveText("开始更新")
//
//                            .positiveColorRes(R.color.back_ground_green)
//                            .onPositive(new MaterialDialog.SingleButtonCallback() {
//                                @Override
//                                public void onClick(@NonNull final MaterialDialog dialog, @NonNull DialogAction which) {
//                                    dialog.dismiss();
//                                    beginReadyFileTrans();
//
//                                }
//                            })
//                            .negativeColorRes(R.color.dialog_bg)
//                            .negativeText(R.string.dialog_negative_text)
//                            .onNegative(new MaterialDialog.SingleButtonCallback() {
//                                @Override
//                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                }
//                            })
//                            .build();
//                    dialog.show();
                } else {
                    Toast.makeText(mContext, "请选择升级文件", Toast.LENGTH_SHORT).show();
                }
                break;
//            default:
//                throw new IllegalStateException("Unexpected value: " + v.getId());
        }
    }

    private void beginReadyFileTrans() {
        if (mList.size() != 0 && ringsCanUpdate) {
            showLoadDialog("正在升级脚环...");
            mList.get(position).setRingUpdate(true);
            mSerialPortUtil.sendFootRing(mList.get(0));
            mSerialPortUtil.closeSerialPort();

            getSomeDate = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        initPort();
                        canStop = true;
                        doWork();
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        Log.d("xxxxx","qeeer");
                        e.printStackTrace();
                    }
                }
            });
            getSomeDate.start();
            startTransmission();
        } else {
            Toast.makeText(mContext, "无可升级脚环", Toast.LENGTH_SHORT).show();
        }
    }

    private MaterialDialog mLoadingDialog;

    public void showLoadDialog(String content) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new MaterialDialog.Builder(this)
                    .progress(true, 0)
                    .content(content)
                    .canceledOnTouchOutside(false)
                    .build();
        } else {
            mLoadingDialog.setContent(content);
        }
        ViewUtil.removeAllKeyListener(mLoadingDialog);
    }

    protected void scanAroundFootRing() {
        EventBusUtil.register(this);
        mSerialPortUtil = SerialPortUtil.getInstance(mContext);
        mSerialPortUtil.openSerialPortToReadData();
        mSerialPortUtil.updateWorking(false);
    }


    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveFootRing(CopyOnWriteArrayList<FootRingNewEntity> list) {
        this.mList = list;
        showFootRingList(list);
    }

    /**
     * 显示脚环列表
     */
    protected void showFootRingList(CopyOnWriteArrayList<FootRingNewEntity> list) {

        if (!list.isEmpty()) {
            if (radarScanView.isShown()) {
                radarScanView.stopAnimation();
                find_page.setVisibility(View.GONE);
                mes_page.setVisibility(View.VISIBLE);
            }
        } else {
            if (!radarScanView.isShown()) {
                radarScanView.startAnimation();
                find_page.setVisibility(View.VISIBLE);
            }
            mes_page.setVisibility(View.GONE);
        }
        mFootRinglist = list;
        if (mRingAdapter == null) {
            mRingAdapter = new UpdateRingAdapter(mFootRinglist, new UpdateRingAdapter.CallBack() {
                @Override
                public void doCheckAll(CompoundButton checkBox, String version) {
                    if (mFirmwareFile != null && mFirmwareFile.exists() && endWith()) {
                        if (getVersionMes(version)) {
                            checkBox.setChecked(!checkBox.isChecked());
                            ringsCanUpdate = checkBox.isChecked();
                        } else {
                            Toast.makeText(FootUpdateActivity.this, "版本非最新，无须升级", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(mContext, "选择一个合法的bin文件", Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void getPosition(int integer) {
                    position = integer;
                }
            });
            searchRingRecycler.setLayoutManager(new LinearLayoutManager(this));
            searchRingRecycler.setAdapter(mRingAdapter);
        } else {
            mRingAdapter.SetRingList(mFootRinglist);
            mRingAdapter.notifyDataSetChanged();
        }
    }

    public Boolean getVersionMes(String version) {
        try {
            String x1=mFirmwareFile.getName().split("-V")[1].split("\\.bin")[0];
            String v1 = getString(x1);
            String v2 = getString(version).split("V")[1];
            Log.d("测试数据", "V1:" + v1 + "   V2:" + v2);
            if (Integer.parseInt(v2) < Integer.parseInt(v1)) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }

        return false;
    }


    public static String getString(String str) {
        StringBuffer stringBuffer = new StringBuffer("");
        String[] demo = str.split("\\.");
        for (int i = 0; i < demo.length; i++) {
            stringBuffer.append(demo[i]);
        }
        return stringBuffer.toString();

    }

    public void dismissLoadingDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }
}